package org.springblade.modules.system.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class QueryParaUtil {

	/**
	 * 清理
	 *
	 * @param source
	 * @param <T>
	 * @return
	 * @throws Exception
	 */
	public static <T> T trim(T source) {
		try {
			Method[] ms = source.getClass().getMethods();
			String name;
			Map<String, Method> setMap = new HashMap<>();
			Map<String, Method> getMap = new HashMap<>();
			for (Method m : ms) {
				name = m.getName();
				if (name.startsWith("set")) {
					setMap.put(name.substring(3), m);
				} else if (name.startsWith("get")) {
					if (m.getReturnType().isAssignableFrom(String.class) && m.getParameterCount() == 0) {
						getMap.put(name.substring(3), m);
					}
				}
			}
			Object value;
			Method setMethod;
			for (Map.Entry<String, Method> entry : getMap.entrySet()) {
				setMethod = setMap.get(entry.getKey());
				if (setMethod == null) {
					continue;
				}
				value = entry.getValue().invoke(source);
				if (value != null && value.toString().length() == 0) {
					String[] arrs = {null};
					setMethod.invoke(source, arrs);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return source;
	}
}
